<template>
  <el-dialog
    v-model="visible"
    title="Excel导入"
    width="60%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="excel-import-container">
      <!-- 步骤条 -->
      <el-steps :active="currentStep" finish-status="success" align-center>
        <el-step title="选择模板" />
        <el-step title="上传文件" />
        <el-step title="配置映射" />
        <el-step title="数据预览" />
        <el-step title="确认导入" />
      </el-steps>

      <!-- 步骤内容 -->
      <div class="step-content">
        <!-- 步骤1: 选择模板 -->
        <div v-if="currentStep === 0" class="step-panel">
          <h3>选择导入模板</h3>
          <el-radio-group v-model="selectedTemplate" @change="handleTemplateChange">
            <div class="template-grid">
              <el-radio 
                v-for="template in templateList" 
                :key="template.type" 
                :label="template.type"
                class="template-item"
              >
                <div class="template-card">
                  <el-icon class="template-icon"><Document /></el-icon>
                  <div class="template-info">
                    <div class="template-name">{{ template.name }}</div>
                    <div class="template-desc">{{ template.description }}</div>
                  </div>
                </div>
              </el-radio>
            </div>
          </el-radio-group>
          
          <div class="step-actions">
            <el-button type="primary" @click="downloadTemplate" :disabled="!selectedTemplate">
              下载模板
            </el-button>
            <el-button type="primary" @click="nextStep" :disabled="!selectedTemplate">
              下一步
            </el-button>
          </div>
        </div>

        <!-- 步骤2: 上传文件 -->
        <div v-if="currentStep === 1" class="step-panel">
          <h3>上传Excel文件</h3>
          <el-upload
            ref="uploadRef"
            class="upload-area"
            drag
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            accept=".xlsx,.xls"
            :limit="1"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传xlsx/xls文件，且不超过10MB
              </div>
            </template>
          </el-upload>
          
          <div v-if="uploadedFile" class="file-info">
            <el-icon><Document /></el-icon>
            <span>{{ uploadedFile.name }}</span>
            <el-button type="text" @click="removeFile">移除</el-button>
          </div>

          <div class="step-actions">
            <el-button @click="prevStep">上一步</el-button>
            <el-button type="primary" @click="nextStep" :disabled="!uploadedFile">
              下一步
            </el-button>
          </div>
        </div>

        <!-- 步骤3: 配置映射 -->
        <div v-if="currentStep === 2" class="step-panel">
          <h3>配置字段映射</h3>
          <div class="mapping-config">
            <el-tabs v-model="activeSheet" @tab-change="handleSheetChange">
              <el-tab-pane 
                v-for="sheet in sheetList" 
                :key="sheet.name" 
                :label="sheet.name" 
                :name="sheet.name"
              >
                <div class="sheet-config">
                  <h4>{{ sheet.name }} - 字段映射配置</h4>
                  <el-table :data="sheet.mappingConfig" border>
                    <el-table-column prop="excelColumn" label="Excel列名" width="200" />
                    <el-table-column label="目标字段" width="200">
                      <template #default="{ row }">
                        <el-select v-model="row.targetField" placeholder="选择目标字段">
                          <el-option
                            v-for="field in targetFields"
                            :key="field.value"
                            :label="field.label"
                            :value="field.value"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="数据类型" width="150">
                      <template #default="{ row }">
                        <el-select v-model="row.dataType" placeholder="选择数据类型">
                          <el-option label="字符串" value="string" />
                          <el-option label="数字" value="number" />
                          <el-option label="日期" value="date" />
                          <el-option label="布尔值" value="boolean" />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="是否必填" width="100">
                      <template #default="{ row }">
                        <el-checkbox v-model="row.required" />
                      </template>
                    </el-table-column>
                    <el-table-column label="验证规则" width="200">
                      <template #default="{ row }">
                        <el-input v-model="row.validationRule" placeholder="验证规则" />
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>

          <div class="step-actions">
            <el-button @click="prevStep">上一步</el-button>
            <el-button type="primary" @click="previewData">预览数据</el-button>
          </div>
        </div>

        <!-- 步骤4: 数据预览 -->
        <div v-if="currentStep === 3" class="step-panel">
          <h3>数据预览</h3>
          <div class="preview-summary">
            <el-alert
              :title="`共解析到 ${previewData.totalRows} 行数据，其中 ${previewData.validRows} 行有效，${previewData.errorRows} 行有错误`"
              type="info"
              show-icon
            />
          </div>

          <el-tabs v-model="activePreviewSheet">
            <el-tab-pane 
              v-for="sheet in previewData.sheets" 
              :key="sheet.name" 
              :label="`${sheet.name} (${sheet.data.length})`" 
              :name="sheet.name"
            >
              <div class="preview-table">
                <el-table :data="sheet.data" border max-height="400">
                  <el-table-column type="index" label="行号" width="60" />
                  <el-table-column
                    v-for="column in sheet.columns"
                    :key="column.prop"
                    :prop="column.prop"
                    :label="column.label"
                    :width="column.width"
                  >
                    <template #default="{ row }">
                      <div :class="{ 'error-cell': row._errors && row._errors[column.prop] }">
                        {{ row[column.prop] }}
                        <el-tooltip
                          v-if="row._errors && row._errors[column.prop]"
                          :content="row._errors[column.prop]"
                          placement="top"
                        >
                          <el-icon class="error-icon"><Warning /></el-icon>
                        </el-tooltip>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
          </el-tabs>

          <div class="step-actions">
            <el-button @click="prevStep">返回配置</el-button>
            <el-button type="primary" @click="nextStep" :disabled="previewData.errorRows > 0">
              确认导入
            </el-button>
          </div>
        </div>

        <!-- 步骤5: 确认导入 -->
        <div v-if="currentStep === 4" class="step-panel">
          <h3>确认导入</h3>
          <div class="import-summary">
            <el-descriptions border :column="2">
              <el-descriptions-item label="导入模板">{{ selectedTemplateName }}</el-descriptions-item>
              <el-descriptions-item label="文件名">{{ uploadedFile?.name }}</el-descriptions-item>
              <el-descriptions-item label="总行数">{{ previewData.totalRows }}</el-descriptions-item>
              <el-descriptions-item label="有效行数">{{ previewData.validRows }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="import-options">
            <h4>导入选项</h4>
            <el-checkbox v-model="importOptions.skipErrors">跳过错误数据</el-checkbox>
            <el-checkbox v-model="importOptions.overwrite">覆盖已存在数据</el-checkbox>
            <el-checkbox v-model="importOptions.createBackup">创建数据备份</el-checkbox>
          </div>

          <div class="step-actions">
            <el-button @click="prevStep">上一步</el-button>
            <el-button 
              type="primary" 
              @click="confirmImport" 
              :loading="importing"
            >
              确认导入
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 导入进度 -->
    <el-dialog v-model="showProgress" title="导入进度" width="30%" :close-on-click-modal="false">
      <el-progress :percentage="importProgress" :status="importStatus" />
      <div class="progress-text">{{ progressText }}</div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, UploadFilled, Warning } from '@element-plus/icons-vue'
import { excelApi } from '@/api/excel'

export default {
  name: 'ExcelImportDialog',
  components: {
    Document,
    UploadFilled,
    Warning
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    businessType: {
      type: String,
      required: true
    }
  },
  emits: ['update:modelValue', 'success'],
  setup(props, { emit }) {
    // 对话框显示状态
    const visible = computed({
      get: () => props.modelValue,
      set: (value) => emit('update:modelValue', value)
    })

    // 当前步骤
    const currentStep = ref(0)

    // 模板相关
    const templateList = ref([])
    const selectedTemplate = ref('')
    const selectedTemplateName = computed(() => {
      const template = templateList.value.find(t => t.type === selectedTemplate.value)
      return template?.name || ''
    })

    // 文件上传相关
    const uploadRef = ref()
    const uploadedFile = ref(null)

    // 映射配置相关
    const sheetList = ref([])
    const activeSheet = ref('')
    const targetFields = ref([])

    // 数据预览相关
    const previewData = ref({
      totalRows: 0,
      validRows: 0,
      errorRows: 0,
      sheets: []
    })
    const activePreviewSheet = ref('')

    // 导入相关
    const importing = ref(false)
    const showProgress = ref(false)
    const importProgress = ref(0)
    const importStatus = ref('')
    const progressText = ref('')
    const importOptions = reactive({
      skipErrors: true,
      overwrite: false,
      createBackup: true
    })

    // 初始化模板列表
    const initTemplateList = async () => {
      try {
        const response = await excelApi.getTemplateList()
        templateList.value = response.data.filter(template => 
          template.businessType === props.businessType
        )
      } catch (error) {
        ElMessage.error('获取模板列表失败')
      }
    }

    // 初始化目标字段
    const initTargetFields = () => {
      // 根据业务类型设置目标字段
      if (props.businessType === 'workOrder') {
        targetFields.value = [
          { label: '工单编号', value: 'workOrderId' },
          { label: '订单编号', value: 'orderId' },
          { label: '产品编号', value: 'productId' },
          { label: '交付日期', value: 'deliveryDate' },
          { label: '数量', value: 'quantity' },
          { label: '优先级', value: 'priority' }
        ]
      }
    }

    // 模板变化处理
    const handleTemplateChange = (templateType) => {
      console.log('handleTemplateChange',templateType)
      selectedTemplate.value = templateType
    }

    // 下载模板
    const downloadTemplate = async () => {
      try {
        const response = await excelApi.downloadTemplate('TestReciveModel')
        console.log("response",response)
        console.log(123123123123)
        const blob = new Blob([response], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `${selectedTemplateName.value}_模板.xlsx`
        link.click()
        console.log("2222222222222")
        window.URL.revokeObjectURL(url)
        ElMessage.success('模板下载成功')
      } catch (error) {
        console.log(error)
        ElMessage.error('模板下载失败')
      }
    }

    // 文件变化处理
    const handleFileChange = (file) => {
      uploadedFile.value = file.raw
    }

    // 文件上传前检查
    const beforeUpload = (file) => {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                     file.type === 'application/vnd.ms-excel'
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isExcel) {
        ElMessage.error('只能上传Excel文件!')
        return false
      }
      if (!isLt10M) {
        ElMessage.error('文件大小不能超过10MB!')
        return false
      }
      return false // 阻止自动上传
    }

    // 移除文件
    const removeFile = () => {
      uploadedFile.value = null
      uploadRef.value?.clearFiles()
    }

    // Sheet变化处理
    const handleSheetChange = (sheetName) => {
      activeSheet.value = sheetName
    }

    // 预览数据
    const previewData = async () => {
      try {
        const config = {
          templateType: selectedTemplate.value,
          mappingConfig: getMappingConfig()
        }
        
        const response = await excelApi.previewExcel(uploadedFile.value, config)
        previewData.value = response.data
        activePreviewSheet.value = previewData.value.sheets[0]?.name || ''
        nextStep()
      } catch (error) {
        ElMessage.error('数据预览失败')
      }
    }

    // 获取映射配置
    const getMappingConfig = () => {
      const config = {}
      sheetList.value.forEach(sheet => {
        config[sheet.name] = sheet.mappingConfig.map(item => ({
          excelColumn: item.excelColumn,
          targetField: item.targetField,
          dataType: item.dataType,
          required: item.required,
          validationRule: item.validationRule
        }))
      })
      return config
    }

    // 确认导入
    const confirmImport = async () => {
      console.log("确认导入")
      try {
        await ElMessageBox.confirm(
          `确定要导入 ${previewData.value.validRows} 条数据吗？`,
          '确认导入',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        importing.value = true
        showProgress.value = true
        importProgress.value = 0
        importStatus.value = 'active'
        progressText.value = '开始导入...'

        const config = {
          templateType: selectedTemplate.value,
          mappingConfig: getMappingConfig(),
          importOptions: importOptions
        }

        // 模拟进度更新
        const progressInterval = setInterval(() => {
          if (importProgress.value < 90) {
            importProgress.value += 10
            progressText.value = `正在导入数据... ${importProgress.value}%`
          }
        }, 200)

        const response = await excelApi.uploadExcel(uploadedFile.value, config)
        
        clearInterval(progressInterval)
        importProgress.value = 100
        importStatus.value = 'success'
        progressText.value = '导入完成！'

        setTimeout(() => {
          showProgress.value = false
          visible.value = false
          emit('success', response.data)
          ElMessage.success('数据导入成功')
        }, 1500)
        
      } catch (error) {
        importing.value = false
        showProgress.value = false
        if (error !== 'cancel') {
          ElMessage.error('数据导入失败')
        }
      }
    }

    // 步骤控制
    const nextStep = () => {
      if (currentStep.value < 4) {
        currentStep.value++
      }
    }

    const prevStep = () => {
      if (currentStep.value > 0) {
        currentStep.value--
      }
    }

    // 关闭对话框
    const handleClose = () => {
      // 重置状态
      currentStep.value = 0
      selectedTemplate.value = ''
      uploadedFile.value = null
      sheetList.value = []
      previewData.value = {
        totalRows: 0,
        validRows: 0,
        errorRows: 0,
        sheets: []
      }
      importing.value = false
      showProgress.value = false
    }

    // 监听对话框显示状态
    watch(visible, (newVal) => {
      if (newVal) {
        initTemplateList()
        initTargetFields()
      }
    })

    return {
      visible,
      currentStep,
      templateList,
      selectedTemplate,
      selectedTemplateName,
      uploadRef,
      uploadedFile,
      sheetList,
      activeSheet,
      targetFields,
      previewData,
      activePreviewSheet,
      importing,
      showProgress,
      importProgress,
      importStatus,
      progressText,
      importOptions,
      handleTemplateChange,
      downloadTemplate,
      handleFileChange,
      beforeUpload,
      removeFile,
      handleSheetChange,
      previewData,
      confirmImport,
      nextStep,
      prevStep,
      handleClose
    }
  }
}
</script>

<style scoped>
.excel-import-container {
  padding: 20px 0;
}

.step-content {
  margin-top: 30px;
  min-height: 400px;
}

.step-panel {
  padding: 20px;
}

.step-actions {
  margin-top: 30px;
  text-align: center;
}

.step-actions .el-button {
  margin: 0 10px;
}

/* 模板选择样式 */
.template-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin: 20px 0;
}

.template-item {
  width: 100%;
}

.template-card {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.template-card:hover {
  border-color: #409eff;
  background-color: #f5f7fa;
}

.template-icon {
  font-size: 32px;
  color: #409eff;
  margin-right: 15px;
}

.template-info {
  flex: 1;
}

.template-name {
  font-weight: 600;
  font-size: 16px;
  margin-bottom: 5px;
}

.template-desc {
  color: #606266;
  font-size: 14px;
}

/* 上传区域样式 */
.upload-area {
  margin: 20px 0;
}

.file-info {
  display: flex;
  align-items: center;
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.file-info .el-icon {
  margin-right: 10px;
  color: #409eff;
}

.file-info span {
  flex: 1;
}

/* 映射配置样式 */
.mapping-config {
  margin: 20px 0;
}

.sheet-config h4 {
  margin-bottom: 15px;
  color: #303133;
}

/* 预览样式 */
.preview-summary {
  margin-bottom: 20px;
}

.preview-table {
  margin-top: 15px;
}

.error-cell {
  color: #f56c6c;
  position: relative;
}

.error-icon {
  color: #f56c6c;
  margin-left: 5px;
}

/* 导入确认样式 */
.import-summary {
  margin-bottom: 20px;
}

.import-options {
  margin: 20px 0;
}

.import-options h4 {
  margin-bottom: 15px;
  color: #303133;
}

.import-options .el-checkbox {
  display: block;
  margin-bottom: 10px;
}

/* 进度对话框样式 */
.progress-text {
  text-align: center;
  margin-top: 15px;
  color: #606266;
}
</style>

